# -*- coding: utf-8 -*-

import json
import logging

from django.views.generic import TemplateView
from django.utils.encoding import smart_unicode
from django.utils.decorators import method_decorator
from common.bankcard import db as bankcard_db
from common.mch import db as mch_db
from common.bankcard import handler as bankcard_handler
from common.utils.decorator import response_wrapper
from common.utils.api import token_required
from common.cache import redis_cache
from common.utils.tz import (
    utc_to_local_str
)
from django.views.decorators.http import require_POST

_LOGGER = logging.getLogger('hydra')


class BankCardView(TemplateView):
    def get(self, req):
        query_dct = req.GET.dict()
        from admin.views import add_query_fliter
        add_query_fliter(req, query_dct)
        items, total_count = bankcard_db.list_bankcard(query_dct)
        resp_items = []
        mch_names = mch_db.get_mch_name_dict()
        for item in items:
            data = item.as_dict()
            data['mch_id'] = mch_names[data['mch_id']]
            data['account_number'] = data['account_number'][0:5] + '*********' + data['account_number'][-5:]
            data['created_at'] = utc_to_local_str(data['created_at'])
            data['updated_at'] = utc_to_local_str(data['updated_at'])
            data['online_status'] = 1 if redis_cache.get_bankcard_online_status(data['name']) else 0
            resp_items.append(data)
        return {'list': resp_items, 'page': query_dct.get('$page', 1),
                'size': len(resp_items), 'total_count': total_count}

    def post(self, req):
        param_dct = json.loads(req.body)
        bankcard = bankcard_db.upsert_bankcard(param_dct)
        return {'id': bankcard.id}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(BankCardView, self).dispatch(*args, **kwargs)


class SingleBankCardView(TemplateView):
    def get(self, req, bankcard_id):
        bankcard = bankcard_db.get_bankcard(id=int(bankcard_id))
        data = bankcard.as_dict()
        data['created_at'] = utc_to_local_str(data['created_at'])
        data['updated_at'] = utc_to_local_str(data['updated_at'])
        return data

    def post(self, req, bankcard_id):
        return self.put(req, bankcard_id)

    def put(self, req, bankcard_id):
        query_dct = json.loads(smart_unicode(req.body))
        bankcard_db.upsert_bankcard(query_dct, int(bankcard_id))
        return {'id': bankcard_id}

    def patch(self, req, bankcard_id):
        query_dct = json.loads(smart_unicode(req.body))
        bankcard_db.upsert_bankcard(query_dct, int(bankcard_id))
        bankcard_handler.card_balance_alert(bankcard_id, req.META['HTTP_HOST'])
        return {'id': bankcard_id}

    def delete(self, req, bankcard_id):
        bankcard_db.delete_bankcard(int(bankcard_id))
        _LOGGER.info('delete bankcard: %s, user: %s', bankcard_id, req.user_id)
        return {'id': bankcard_id}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(SingleBankCardView, self).dispatch(*args, **kwargs)


@require_POST
@response_wrapper
@token_required
def get_bankcard_recharge_url(req):
    _LOGGER.info('set_agency_rest: %s', req.body)
    query_dct = json.loads(smart_unicode(req.body))
    try:
        amount = float(query_dct['amount'])
    except Exception:
        amount = None
    url = bankcard_handler.get_bankcard_pay_url(query_dct['id'], amount)
    return {'id': query_dct['id'], 'url': url}